import * as TokenFunction from "@/assets/js/TokenFunction";
import * as HrefLocation from "@/assets/js/HrefLocation";
import LoginDiv from "@/components/Login/LoginDiv.vue";
import axios from "axios";
import {INDEXURL} from "@/assets/js/HrefLocation";

export async function checkLogin(vm) {

    var authorization = localStorage.getItem("token");
    let isTokenAlive;
    //async return出来是Promise对象，需要从中才能获得原来函数return的值
    await TokenFunction.checkTokenValidation().then((result) => {
        isTokenAlive = result

    })
    console.log(isTokenAlive)
    vm.isLoggedIn = false;

    if (authorization && isTokenAlive) {

        vm.isLoggedIn = true
        vm.userName1 = TokenFunction.getUserInfoFromToken('userName')
        vm.userId1 = TokenFunction.getUserInfoFromToken('userId')
        vm.administratorId1 = TokenFunction.getUserInfoFromToken('administratorId')
        vm.administratorCategory1 = TokenFunction.getUserInfoFromToken('administratorCategory')
    }else{
        localStorage.removeItem("token");
    }
}

export function cancelLogin() {
    localStorage.removeItem("token");
    this.isLoggedIn = false;  // 更新响应式属性
    window.location.href = HrefLocation.INDEXURL;
}

export function login() {
    var userName=this.loginForm.username;
    var userPsd=this.loginForm.password;
    axios.post("/hkgapi/user/login",{
        userName:userName,
        userPsd:userPsd
    }).then(res=>{
        if(res.data.code===0){
            //放入token
            localStorage.setItem("token",res.data.data)

            window.location.href=INDEXURL
        }else{
            this.$alert("登录失败："+res.data.message,"登录失败")
        }

    }).catch(error=>{
        console.log(error)
    })
}